<!--
 * @Author: Aaron
 * @Date: 2022-05-05 14:26:56
 * @LastEditors: Aaron Huang
 * @LastEditTime: 2022-10-14 17:55:20
 * @Description: file content
 * @FilePath: \ias_ui\src\views\JDSupermarket\index\list.vue
 * @Company: 沃尔玛
-->
<template>
  <div v-loading="loading" class="products-list">
    <searchHead :search-list="searchList" :search-data="searchData" @handleSearch="handleSearch" @handleReset="handleReset" @handleDownload="handleDownload" />

    <essTable
      ref="table"
      :thead-list="theadList(isEdit)"
      :other-container-box="otherContainerBox"
      :resize-observer-ele="resizeObserverEle"
      :total="total"
      :data-list="dataList"
      :page-params="pageParams"
      :selectable="selectable"
      @handlePageChange="requestData"
      @selectionChange="selectionChange"
      @viewDetails="viewDetails"
    >
      <template v-slot:upcStatus="{ scope }">{{ scope | transUpcStatus }}</template>
      <div slot="left">
        <el-button class="BtnLog" size="mini" icon="el-icon-tickets" round @click="viewLog">操作日志</el-button>
      </div>
      <div v-if="isEdit" slot="right" class="mb-8">
        <i class="el-icon-refresh" title="点击刷新列表数据" @click="handleSearch" />
        <b>批量操作：</b>
        <el-button size="mini" type="primary" icon="el-icon-plus" round @click="addOffer">新增/更新报价</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" round :disabled="!hasSelect" @click="delOffer">删除报价</el-button>
      </div>
    </essTable>
    <purchaseLog
      v-model="logVisible"
      width="1000px"
      title="操作日志"
      :thead-list="operationLogTableHeader"
      :data-list="operationLogTableList"
      :slot-list="['left']"
      :total="total2"
      :slot-custom="true"
      :page-params="logform"
      :pagination-show="true"
      @handlePageChange="handlePageChange"
    >
      <template v-slot:left>
        <el-form class="searchform" :inline="true" size="mini" label-width="auto">
          <el-form-item label="UPC(不带校验)">
            <el-input v-model.trim="logform.upc" placeholder="请输入UPC,必填" clearable @input="inputUpc" />
          </el-form-item>
          <el-form-item label="门店号">
            <el-input v-model.trim="logform.storeNbr" placeholder="请输入门店号" clearable @input="inputStoreNbr" />
          </el-form-item>
          <el-form-item>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-search"
              round
              :disabled="!(logform.upc && logform.upc.length > 0)"
              @click="handlePageChange({ pageNum: 1, pageSize: 10 })"
            >
              查 询
            </el-button>
          </el-form-item>
        </el-form>
      </template>
    </purchaseLog>
  </div>
</template>

<script>
import searchHead from '@/components/searchHead/searchHead.vue'
import essTable from '@/components/eTable/eTable.vue'
import moment from 'moment'
import bus from '@/utils/eventBus.js'
import { productsListHeader as theadList, operationLogTableHeader } from '../js/theadList.js'
import { tableParams, searchHeaderEvent } from '@/components/eTable/js/mixins.js'
import { productList, productListAll, delOfferApi, productListExport, productListExportAll, handleLog } from '@/api/JDSupermarket/productsList.js'
import { stringToArray, filterKey } from '@/utils/processingData.js'
import { upcStatus, enumerationUpcStatus } from '../js/dictionary.js'
import { hasEdit } from '../js/hasEdit.js'
import purchaseLog from '@/components/dialogTableInfo/dialogTableInfo.vue'

export default {
  name: 'JDSupermarketProducts',
  components: {
    searchHead,
    essTable,
    purchaseLog
  },
  filters: {
    transUpcStatus({ row }) {
      return filterKey(row.upcStatus, upcStatus)
    }
  },
  mixins: [tableParams, searchHeaderEvent, hasEdit],
  data() {
    return {
      loading: false,
      searchData: {},
      searchList: [
        { label: 'UPC(不含检验码)', type: 'textarea', value: 'skuList' },
        { label: '京东商品编号', type: 'textarea', value: 'jdSkuIdList' },
        { label: '商品名称', type: 'input', value: 'skuName', maxlength: 50 },
        { label: '部门', type: 'textarea', value: 'deptNbrList' },
        { label: 'Fineline', type: 'textarea', value: 'finelineNbrList' }
      ],
      theadList,
      otherContainerBox: ['.app-container'],
      resizeObserverEle: ['.app-main', '.app-container'],
      selectable({ upcStatus }) {
        return Boolean(upcStatus === enumerationUpcStatus.TAKEEFFECT)
      },
      queryListFun: null,
      exportFun: null,
      logVisible: false,
      operationLogTableHeader,
      operationLogTableList: [],
      logform: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      total2: 0
    }
  },
  computed: {
    hasSelect() {
      return Boolean(
        Array.isArray(this.multipleSelection) &&
          this.multipleSelection.length &&
          this.multipleSelection.every((_) => _.upcStatus === enumerationUpcStatus.TAKEEFFECT)
      )
    }
  },
  mounted() {
    this.chooseQueryListFun()
    this.requestData()
  },
  methods: {
    inputUpc(val) {
      this.logform.upc = val.replace(/[^\d]/g, '')
    },
    inputStoreNbr(val) {
      this.logform.storeNbr = val.replace(/[^\d]/g, '')
    },
    chooseQueryListFun() {
      if (this.isEdit) {
        this.queryListFun = productList
        this.exportFun = productListExport
      }
      if (this.isAdministrators) {
        this.queryListFun = productListAll
        this.exportFun = productListExportAll
      }
    },
    handleSearchData() {
      const queryData = JSON.parse(JSON.stringify({ ...this.pageParams, ...this.searchData }))
      queryData.pageNum--
      const regExp = new RegExp(/\D/, 'g')
      if (queryData?.skuName?.length > 50) throw new Error('商品名称长度大于50！')
      if ('skuList' in queryData) {
        queryData.skuList = stringToArray(queryData.skuList, /[\n\r]/)
        queryData.skuList.forEach((_) => {
          if (regExp.test(_)) throw new Error(`UPC(不含检验码)只能输入数字，${_} 包含非法字符！`)
          if (_.length > 12) throw new Error(`UPC(不含检验码)最长12位，${_} 长度大于12！`)
        })
        if (queryData.skuList?.length > 100) throw new Error('UPC(不含检验码)数量大于100条')
        queryData.skuList = queryData.skuList.map(Number)
      }
      if ('jdSkuIdList' in queryData) {
        queryData.jdSkuIdList = stringToArray(queryData.jdSkuIdList, /[\n\r]/)
        queryData.jdSkuIdList.forEach((_) => {
          if (regExp.test(_)) throw new Error(`京东商品编号只能输入数字， ${_} 包含非法字符！`)
          if (_.length > 20) throw new Error(`京东商品编号最长20位 ${_} 长度大于20！`)
        })
        if (queryData.jdSkuIdList?.length > 100) throw new Error('京东商品编号数量大于100条')
      }
      if ('deptNbrList' in queryData) {
        queryData.deptNbrList = stringToArray(queryData.deptNbrList, /[\n\r]/)
        queryData.deptNbrList.forEach((_) => {
          if (regExp.test(_)) throw new Error(`部门号只能输入数字， ${_} 包含非法字符！`)
          if (_.length > 2) throw new Error(`部门号最长2位，${_} 长度大于2！`)
        })
        if (queryData.deptNbrList?.length > 100) throw new Error('部门数量大于100条')
      }
      if ('finelineNbrList' in queryData) {
        queryData.finelineNbrList = stringToArray(queryData.finelineNbrList, /[\n\r]/)
        queryData.finelineNbrList.forEach((_) => {
          if (regExp.test(_)) throw new Error(`Fineline只能输入数字 ${_} 包含非法字符！`)
          if (_.length > 4) throw new Error(`Fineline最长4位， ${_} 长度大于4！`)
        })
        if (queryData.finelineNbrList?.length > 100) throw new Error('Fineline数量大于100条')
      }
      return queryData
    },

    async requestData() {
      try {
        this.loading = true
        if (!this.queryListFun) throw new Error('当前角色不支持查看该列表信息')
        const { code, result } = await this.queryListFun(this.handleSearchData())
        if (code !== '0') return
        this.total = result.total
        this.dataList = result.data || []
      } catch (e) {
        if (e?.message) this.$message.error(e)
      } finally {
        this.loading = false
      }
    },

    async handleDownload() {
      try {
        this.loading = true
        const date = moment(new Date()).format('YYYY-MM-DD')
        await this.exportFun(this.handleSearchData(), `京超商品 ${date}`)
      } finally {
        this.loading = false
      }
    },

    addOffer() {
      this.$router.push({
        name: 'JDSupermarketProductOffer'
      })
    },

    delOffer() {
      this.$confirm('删除报价, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(this.delOfferRequery)
        .catch(() => {})
    },
    async delOfferRequery() {
      try {
        const { code } = await delOfferApi(this.multipleSelection.map((_) => _.id))
        if (code !== '0') return
        this.$message({
          type: 'success',
          message: '已对该商品发起删除报价操作！'
        })
        this.handleSearch()
      } catch (error) {
        console.log(error)
      }
    },
    viewDetails(v) {
      const { id, upc, skuName, jdSkuId } = v.row
      bus.$emit('setTagName', `${skuName} - 报价详情`)
      this.$router.push({
        name: 'JDSupermarketProductDetails',
        params: {
          id
        },
        query: {
          skuName,
          jdSkuId,
          upc
        }
      })
    },
    viewLog() {
      this.total = 0
      this.operationLogTableList = []
      this.logform = {
        pageNum: 0,
        pageSize: 10
      }
      this.logVisible = true
    },
    handlePageChange(val) {
      this.logform.pageNum = val.pageNum
      this.logform.pageSize = val.pageSize
      this.operationLog()
    },
    async operationLog() {
      const param = JSON.parse(JSON.stringify(this.logform))
      param.pageNum = param.pageNum - 1
      const { result } = await handleLog(param)
      this.total2 = 0
      this.operationLogTableList = []
      if (result && Array.isArray(result.data) && result.data.length) {
        this.total2 = result.total
        this.operationLogTableList = result.data
      } else {
        this.$message.error('暂无操作日志')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.products-list {
  .mb-8 {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
}

.el-icon-refresh {
  margin: 0 20px;
  font-size: 22px;
  color: #0071ce;
  cursor: pointer;
}
/deep/.el-dialog__body {
  padding-top: 10px !important;
}
.BtnLog {
  color: #409eff !important;
}
</style>
